//ip配置
// var defaultUrl = 'http://192.168.1.40:8088';
//var defaultUrl = 'http://192.168.1.232:8088';
// var defaultUrl = 'http://192.168.1.38:8088';
 var defaultUrl = 'http://192.168.1.75:8088';
// var defaultUrl = 'http://192.168.1.155:8088';
// var defaultUrl = 'http://36.7.136.132:8088';

//默认图片配置
//模板菜单图片
var m_init_icon = '/static/IMG/mouldinit.png';
//用户头像默认图片
var u_init_icon = '/static/IMG/user.png';

//数据模块缩略图默认图片
var data_init_thumb = '/static/IMG/'

//ajaxPOST请求统一方法
function ajaxPost(url, data, success, error) {
    var loadIndex = layer.load(2)
    //是否是从未登录
    // if (!getLocalStorage('JSXM') || !getLocalStorage('JSXM').userCount) {
    //     sysPopups('账号登录','./HTML/login/login.html',400,310,'')
    //     return
    // }
    $.ajax({
        type: 'POST',
        url: url,
        data: JSON.stringify(data),
        dataType: 'json',
        contentType: 'application/json',
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function (data) {
            layer.close(loadIndex);
            if (data.code === 200) {
                if (success !== 'undefined' && typeof success === 'function') {
                    success(data)
                }
            } else if (data.code === 302) {
                sysPopups('账号登录','./HTML/login/login.html',400,310,'')
            } else if (data.message) {
                layer.msg(data.message)
            }
        },
        error: function (data) {
            if (error !== 'undefined' && typeof error === 'function') {
                error(data)
            }
        }
    })
}

//ajaxGET请求统一方法
function ajaxGet(url, data, success, error) {
    var loadIndex = layer.load(2)
    //是否是从未登录
    // if (!getLocalStorage('JSXM') || !getLocalStorage('JSXM').userCount) {
    //     sysPopups('账号登录','./HTML/login/login.html',400,310,'')
    //     return
    // }
    $.ajax({
        type: 'GET',
        url: url,
        data: data,
        dataType: 'json',
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function (data) {
            layer.close(loadIndex);
            if (data.code === 200) {
                if (success !== 'undefined' && typeof success === 'function') {
                    success(data)
                }
            } else if (data.code === 302) {
                sysPopups('账号登录','./HTML/login/login.html',400,310,'')
            } else if (data.message) {
                layer.msg(data.message)
            }
        },
        error: function (data) {
            if (error !== 'undefined' && typeof error === 'function') {
                error(data)
            }
        }
    })
}

//上传文件统一方法
function ajaxFile(url, data, success, error) {
    var loadIndex = layer.load(2)
    //是否是从未登录
    if (!getLocalStorage('JSXM') || !getLocalStorage('JSXM').userCount) {
        sysPopups('账号登录','./HTML/login/login.html',400,310,'')
        return
    }
    $.ajax({
        type: 'POST',
        url: url,
        data: data,
        dataType: 'json',
        processData: false,
        contentType: false,
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function (data) {
            layer.close(loadIndex);
            if (data.code === 200) {
                if (success !== 'undefined' && typeof success === 'function') {
                    success(data)
                }
            } else if (data.code === 302) {
                sysPopups('账号登录','./HTML/login/login.html',400,310,'')
            } else if (data.message) {
                layer.msg(data.message)
            }
        },
        error: function (data) {
            if (error !== 'undefined' && typeof error === 'function') {
                error(data)
            }
        }
    })
}

//系统弹出框统一方法全部居中显示 （不包括应用内弹出框） sysPopupf 弹出框类型为1 sysPopups弹出框类型为2
var fIndex = null,sIndex = null;
function sysPopupf(title,url,width,height,lfn,btn,bfn1,bfn2) {
    var cancelFn = null
        ,successFn = null
        ,endFn = null;
    for (key in lfn) {
        cancelFn = (key == 'cancel') ? lfn[key] : cancelFn;
        successFn = (key == 'success') ? lfn[key] : successFn;
        endFn = (key == 'end') ? lfn[key] : endFn;
    }
    btn = typeof btn === 'object' ? btn : [];
    fIndex = layer.open({
        title: title,
        type: 1, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        skin: 'layerCls',
        shade: .2,
        anim: -1,
        btn: btn,
        resize:false,
        isOutAnim: false,
        area: [width+'px', height+'px'],
        content: url, //这里content是一个普通的String
        success: function (layero, index) {
            if(successFn && typeof successFn === 'function'){
                successFn();
            }
        },
        end:function (layero,index) {
            if(endFn && typeof endFn === 'function'){
                endFn();
            }
        },
        cancel:function (layero,index) {
            if(cancelFn && typeof cancelFn === 'function'){
                cancelFn();
            }
        },
        yes:function (index,layero) {
            typeof bfn1 === 'function' ? bfn1(index,layero) : ''
        },
        btn1:function (index,layero) {
            typeof bfn2 === 'function' ? bfn2(index,layero) : ''
        }
    })
}
function sysPopups(title,url,width,height,lfn) {
    layer.close(sIndex);
    var cancelFn = null
        ,successFn = null
        ,endFn = null;
    for (key in lfn) {
        cancelFn = (key == 'cancel') ? lfn[key] : cancelFn;
        successFn = (key == 'success') ? lfn[key] : successFn;
        endFn = (key == 'end') ? lfn[key] : endFn;
    }
    sIndex = layer.open({
        title: title,
        type: 2, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        skin: 'layerCls',
        shade: .2,
        anim: -1,
        resize:false,
        isOutAnim: false,
        area: [width+'px', height+'px'],
        content: url, //这里content是一个普通的String
        success: function (layero, index) {
            if(successFn && typeof successFn === 'function'){
                successFn();
            }
        },
        end:function (layero,index) {
            if(endFn && typeof endFn === 'function'){
                endFn();
            }
        },
        cancel:function (layero,index) {
            if(cancelFn && typeof cancelFn === 'function'){
                cancelFn();
            }
        }
    })
}


//向本地存储数据
function setLocalStorage(key, value, days) {
    // 设置过期原则
    if (!value) {
        localStorage.removeItem(key)
    } else {
        var Days = days || 1; // 默认保留1天
        var exp = new Date();
        localStorage[key] = JSON.stringify({
            value,
            expires: exp.getTime() + Days * 24 * 60 * 60 * 1000
        })
    }
}

//获取本地存储数据
function getLocalStorage(key) {
    try {
        let o = JSON.parse(localStorage[key])
        if (!o || o.expires < Date.now()) {
            return false
        } else {
            return o.value
        }
    } catch (e) {
        // 兼容其他localstorage
        console.log(e)
        return localStorage[key]
    } finally {
    }
}


//截屏获取图片
function screenshots(dom, fn) {
    new html2canvas(dom).then(canvas => {
        //弹出截屏页面
        screenIndex = layer.open({
            title: '剪切封面',
            type: 2, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
            skin: 'layerCls',
            btn: ['上传本地', '裁剪'],
            shade: .2,
            anim: -1,
            isOutAnim: false,
            area: ['800px', '580px'],
            content: './HTML/Screenshot.html', //这里content是一个普通的String
            success: function(layero, index) {
                layero.find('iframe')[0].contentWindow.bl = 93 / 50;
                layero.find('iframe').contents().find('#screenImg').attr('src',canvas.toDataURL("image/png",0.8));
            },
            yes: function (index, layero) {
                //上传本地图片
                layero.find('iframe').contents().find('.localUpload').click();
                layero.find('iframe').contents().find('.localUpload').on("change", function () {
                    var files = this.files;
                    if (files && files.length) {
                        var file = files[0];
                        if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
                            var uploadedImageURL = window.URL.createObjectURL(file);
                            //销毁上一个cropper对象 并对新上传的图片进行cropper初始化
                            layero.find('iframe').contents().find('#screenImg').attr('src', '');
                            layero.find('iframe')[0].contentWindow.destroyCropped();
                            layero.find('iframe').contents().find('#screenImg').attr('src', uploadedImageURL);
                            layero.find('iframe')[0].contentWindow.initCropped();
                        } else {
                            layer.msg('请选择正确的图片格式！');
                        }
                    }
                });
                return false
            },
            btn2: function (index, layero) {
                //获取cropper返回的图片base64字节码
                var Base64 = layero.find('iframe')[0].contentWindow.getCroppedCanvas();
                //将base64压缩转化为blob对象
                compress(Base64,function (data) {
                    var Blob = convertBase64UrlToBlob(data, "png");
                    fn(data, Blob)
                });
            }
        })
    });
}

// 修改头像
function modifyPicture(src,fn){
    modifyIndex = layer.open({
        title: '修改头像',
        type: 2, //0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
        skin: 'layerCls',
        btn: ['上传本地', '裁剪'],
        shade: .2,
        anim: -1,
        isOutAnim:false,
        area: ['800px', '600px'],
        content: './HTML/Screenshot.html', //这里content是一个普通的String
        success: function(layero, index) {
            // 图片裁剪比例
            layero.find('iframe')[0].contentWindow.bl = 1 / 1;
            layero.find('iframe').contents().find('#screenImg').attr('src',src)
        },
        yes:function (index,layero) {
            //上传本地图片
            layero.find('iframe').contents().find('.localUpload').click();
            layero.find('iframe').contents().find('.localUpload').on("change", function() {
                var files = this.files;
                if (files && files.length) {
                    var file = files[0];
                    if (/\.(gif|jpg|jpeg|png|GIF|JPG|PNG)$/.test(file.name)) {
                        var uploadedImageURL = window.URL.createObjectURL(file);
                        //销毁上一个cropper对象 并对新上传的图片进行cropper初始化
                        layero.find('iframe').contents().find('#screenImg').attr('src','');
                        layero.find('iframe')[0].contentWindow.destroyCropped();
                        layero.find('iframe').contents().find('#screenImg').attr('src',uploadedImageURL);
                        layero.find('iframe')[0].contentWindow.initCropped();
                    } else {
                        layer.msg('请选择正确的图片格式！');
                    }
                }
            });
            return false
        },
        btn2:function (index,layero) {
            //获取cropper返回的图片base64字节码
            var Base64 = layero.find('iframe')[0].contentWindow.getCroppedCanvas();
            //将base64转化为blob对象
            var Blob=convertBase64UrlToBlob(Base64,"png");
            fn(Base64,Blob)
        }
    })
}

//图片压缩
//base64 图片格式 fn 获取压缩后的数据并回调s
function compress(base64,fn) {
    var img = new Image();
    img.src = base64;
    img.onload = function () {
        var width = img.width = 352;
        var height = img.height = 190;
        var canvas = document.createElement("canvas");
        var ctx = canvas.getContext('2d');
        var tCanvas = document.createElement("canvas");
        var tctx = tCanvas.getContext("2d");
        // 如果图片大于四百万像素，计算压缩比并将大小压至400万以下
        var ratio;
        if ((ratio = width * height / 4000000) > 1) {
            ratio = Math.sqrt(ratio);
            width /= ratio;
            height /= ratio;
        } else {
            ratio = 1;
        }
        canvas.width = width;
        canvas.height = height;
        // 如果图片像素大于100万则使用瓦片绘制
        var count;
        if ((count = width * height / 1000000) > 1) {
            count = Math.sqrt(count) + 1; // 计算要分成多少块瓦片
            // 计算每块瓦片的宽和高
            var nw = width / count;
            var nh = height / count;
            tCanvas.width = nw;
            tCanvas.height = nh;
            for (var i = 0; i < count; i++) {
                for (var j = 0; j < count; j++) {
                    tctx.drawImage(img, i * nw * ratio, j * nh * ratio, nw * ratio, nh * ratio, 0, 0, nw, nh);
                    ctx.drawImage(tCanvas, i * nw, j * nh, nw, nh);
                }
            }
        } else {
            ctx.drawImage(img, 0, 0, width, height);
        }
        // 进行最小压缩
        var ndata = canvas.toDataURL('image/png', .1);
        tCanvas.width = tCanvas.height = canvas.width = canvas.height = 0;
        fn(ndata)
    }

}

function convertBase64UrlToBlob(urlData,type){
    var bytes=window.atob(urlData.split(',')[1]);        //去掉url的头，并转换为byte
    //处理异常,将ascii码小于0的转换为大于0
    var ab = new ArrayBuffer(bytes.length);
    var ia = new Uint8Array(ab);
    for (var i = 0; i < bytes.length; i++) {
        ia[i] = bytes.charCodeAt(i);
    }
    return new Blob([ab], {type: 'image/' + type});
}

//系统流加载统一方法 post请求和get请求
//当前请求数据列表的页码
//status 0进入审核中 1审核通过 2保存草稿箱中 3审核未通过
//url请求路径 page当前请求的页码 param请求参数  flow流对象 fn回调函数一般是将数据生成html的方法 type类型当前容器的唯一标记 type2类型 0表示获取数据并追加 1表示获取数据进行覆盖
var total = 2;
var limit = 5;
function getFlowDataByPost(url,param,page,flow,fn,type,type2) {
    param.ispage = true;
    param.limit = limit;
    param.page  = page;
    ajaxPost(url, param,function (data) {
            if (data.code === 200) {
                typeof fn === 'function' ?  fn(data.data,type,type2) : '';
                total = Math.ceil(parseInt(data.totle)/limit);
                //实现流加载
                flow.load({
                    elem: '.'+type //指定列表容器
                    ,isAuto: false
                    ,done: function(page, next){ //到达临界点（默认滚动触发），触发下一页
                        if (page > 1) {
                            getLevelDataByPost(url,param,page,flow,fn,type,0);
                        }
                        next('',page < total,data.data.length);
                    }
                });
            }
        })
}

function getLevelDataByPost(url,param,page,flow,fn,type,type2) {
    param.ispage = true;
    param.limit = limit;
    param.page  = page;
    ajaxPost(url, param,function (data) {
        if (data.code === 200) {
            typeof fn === 'function' ?  fn(data.data,type,type2) : '';
        }
    })
}


// 接受其他页面的传值
function getUrlParam(serach, name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)") // 构造一个含有目标参数的正则表达式对象
    r = serach.substr(1).match(reg);        // 匹配目标参数
    if (r != null) return decodeURI(r[2]);  // 返回参数值
    return null;  // 如果不存在，返回null
}

//窗口改变自适应事件
function resizeAdapt() {
    $(window).resize(function () {
        var h = $(window).height() - 60;
        $('#view').height(h);
    })
}

//窗口关闭时触发
function onbeforeunload_handler() {
    loginOut(1)
}

// 退出登录删除cookie
// type 类型 0表示个人中心的退出登录 1表示关闭浏览器退出登录
function loginOut(type) {
    ajaxGet(defaultUrl + '/session/list', {'username': getLocalStorage('JSXM').user}, function (data) {
        if (data.code === 200 && data.data.length > 0) {
            for (var i = 0, l = data.data.length; i < l; i++) {
                if (data.data[i].current) {
                    var id = data.data[i].id;
                    //调用删除id接口
                    $.ajax({
                        url: defaultUrl + '/session/delete/' + id,
                        type: 'GET',
                        dataType: 'json',
                        xhrFields: {
                            withCredentials: true // 这里设置了withCredentials
                        },
                        success: function (data) {
                            if (data.code === 200) {
                                if (!type) {
                                    location.reload();
                                } else {
                                    //发送离线的消息推送
                                    send(JSON.stringify({}));
                                }
                                localStorage.removeItem('JSXM');
                            }
                        },
                        error: function (data) {
                        }
                    })
                    break
                }
            }
        }
    })
}